﻿/****************************************************************************
Copyright (c) 2014-2015 凌惊雪 微信:Lingjingxue 邮箱:lingjingxue@sina.com QQ:271487457

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

using UtilLib;
using UtilPublic.ServerLoger;
using ServerBase.DataBaseRedis;
using ServerBase.Protocol;
using ServerBase.Other;
using System.Collections.Generic;
using static UtilPublic.Redis.ServerRedis;
using static ServerGame.Service.Dispatcher;
using UtilPublic.Serialization;
using ServerGame.Service;
using static ServerBase.Config.Conf;
using ServerBase.Service;
using UtilPublic.Mysql;
using static ServerBase.DataBaseRedis.RdsTxt;
using static ServerBase.Service.BaseDispatch;
using ServerBase.Config;
using ServerBase.IniFile;
using ServerPublic.Manager;
using System;
using static ServerBase.IniFile.IniConf;
using ServerGame.GameObject;
using System.Net;
using System.Linq;
using ServerPublic.DataBaseMysql;
using ServerPublic.Data;
using ServerGame.Data;
using ServerBase.LunarSocket;

namespace ServerGame.Manager
{
    /// <summary>
    /// 玩家登陆管理器
    /// </summary>
    public static class LoginMgr
    {

        
        // 自动存储
        public static bool AutoSave(this Player player)
        {
            loger.Debug("AutoSave");

            return player.Save();
        }

        // 玩家登入
        public static void PlayerLoginOn(this Player player)
        {
            player.DaMisc.TicksLastLogin = DateTime.Now.Ticks;

            //设置连接已登陆
            player.Session.Loginded = true;

            //日志
            (ERecordType.登录游戏, EActionSource.系统).RecData(player.Uid, new DateTime(player.DaMisc.TicksRegister), player.IpAddress);

            DataGame.DictPlayerOnline[player.Uid] = player;
            player.SetActive();
            DataGame.DictPlayerCache[player.Uid] = player;
        }

        // 玩家注销
        public static void PlayerLoginOut(this Player player)
        {
            player.DaMisc.TicksLastLogout = DateTime.Now.Ticks;

            player.AutoSave();

            var 本次在线时长 = new TimeSpan(player.DaMisc.TicksLastLogout - player.DaMisc.TicksLastLogin);
            //日志
            (ERecordType.退出游戏, EActionSource.系统).Rec(player.Uid, player.IpAddress, 本次在线时长.TotalSeconds);

            //设置连接已断开
            player.Session.Loginded = false;

            //离线
            DataGame.DictPlayerOnline.Remove(player.Puid);

            loger.Info($"玩家注销: PUID: {player.Uid} 名字: {player.Name} 成功");
        }

        //检查姓名
        public static EProtocolResult CheckPlayerName(string name)
        {
            var rst = NameMgr.CheckName(name);
            if (rst != EProtocolResult.成功)
            {
                return rst;
            }

            long puid = AHashGet(RdsPlayerNamePuid, name).ToLong();
            if (puid != 0)
            {
                return EProtocolResult.名字已经被使用;
            }
            return EProtocolResult.成功;
        }

        // 玩家修改名字
        public static EProtocolResult PlayerChangeName(Player player, string newName)
        {
            string oldName = player.Name;
            var rst = CheckPlayerName(newName);
            if (rst == EProtocolResult.成功)
            {
                AHashDelete(RdsPlayerNamePuid, oldName);
                AHashSet(RdsPlayerPuidName, player.Uid, newName);
                AHashSet(RdsPlayerNamePuid, newName, player.Uid);

                player.Name = newName;

                ////日志
                //Record.Rec(ERecordType.eRecordType更改昵称, player.Id,
                //    oldName, newName);

                player.Save();
            }
            return rst;
        }

        // 玩家创建
        public static EProtocolResult PlayerCreate(LunarSession session
            , bool isfast = false
            , string _name = "puid"
            , string _gender = "男性"
            , string _family = "")
        {
            var name = _name;
            var family = _family;
            var gender = _gender;

            var puid = session.Puid;

            //if (!isfast && puid == 0)
            //{
            //    return EProtocolResult.请先登录;
            //}
            if (puid == 0)
            {
                session.Puid = IdMgr.CreatePuid();
                puid = session.Puid;
            }
            if (puid == 0)
            {
                return EProtocolResult.服务器数据库异常;
            }

            //插入玩家数据
            var player = new Player(puid, session);

            if (isfast)
            {
                name = $"{NameMgr.GetName()}";
                gender = (new List<string>() { "男性", "女性" }).RandomSingle();
            }
            else
            {
                EProtocolResult checkresult = CheckPlayerName(name);
                if ((short)checkresult != 0)
                {
                    return checkresult;
                }
            }
            if (!ConfFamily.ContainsKey(family))
            {
                family = ConfFamily.Keys.First();
            }

            DataGame.ServerListPuidAdd(puid);

            player.DaMisc.TicksRegister = DateTime.Now.Ticks;
            player.InitNewbieData(name, gender, family);
            player.InitPlayerData();
            player.InitNewbieData2();

            player.PlayerLoginOn();

            if (!player.SaveNewbie())
            {
                return EProtocolResult.服务器数据库异常;
            }

            //绑定玩家
            session.SessionObj = player;

            (ERecordType.注册游戏, EActionSource.系统).Rec(player.Uid, player.IpAddress, player.Name);

            return EProtocolResult.成功;
        }

        // 玩家登陆
        public static EProtocolResult PlayerLogin(LunarSession session)
        {
            var puid = session.Puid;

            //如果玩家已在线
            if (DataGame.DictPlayerOnline.TryGetValue(puid, out var player))
            {
                //如果相同连接 忽略
                if (player.SessionID != session.Sid)
                {
                    //通知玩家被取代 断掉原来的连接
                    PlayerBeReplaced(player);
                }
            }
            //如果玩家在缓存
            else if (DataGame.DictPlayerCache.TryGetValue(puid, out player))
            {
                //如果相同连接 忽略
                if (player.SessionID != session.Sid)
                {
                    player.InitPlayerData();
                    player.Save();
                }
            }
            else
            {
                player = new Player(puid, session);

                //判断玩家数据是否存在
                if (!player.Load())
                {
                    return EProtocolResult.服务器数据库异常;
                }
                player.InitPlayerData();

                //老玩家快照，适配玩家未保存时查看排行榜
                player.Save();
            }

            //查询是否被封禁
            if (player.DaMisc.IsBan())
            {
                return EProtocolResult.玩家被封禁;
            }

            player.SessionID = session.Sid;
            player.Session = session;

            player.PlayerLoginOn();

            //绑定玩家
            session.SessionObj = player;

            return EProtocolResult.成功;
        }

        /// 通知玩家被取代
        public static void PlayerBeReplaced(Player player)
        {
            var oldSession = player.Session;
            if (oldSession != null)
            {
                // todo 是否断开被取代的 不断开连接
                oldSession.TryClose();

                //设置连接ID类型
                oldSession.SessionUuid = 0;
                oldSession.SessionType = 0;

                var Rsp = new G2C_Login_Replaced();
                oldSession.Send(Rsp);
            }
        }

        //通知玩家被封号
        public static void PlayerBeBan(Player player)
        {
            var Rsp = new G2C_Login_Ban();
            player.Send(Rsp);
        }

        

    }
}